<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\Category;
use App\Models\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;

class UserPostController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * 显示创建文章页面
     */
    public function create()
    {
        $categories = Category::where('is_active', true)->get();
        $tags = Tag::all();

        return Inertia::render('Post/Create', [
            'categories' => $categories,
            'tags' => $tags,
        ]);
    }

    /**
     * 保存新文章
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:posts',
            'content' => 'required|string',
            'excerpt' => 'nullable|string|max:500',
            'category_id' => 'required|exists:categories,id',
            'tags' => 'array',
            'tags.*' => 'exists:tags,id',
            'featured_image' => 'nullable|image|max:2048',
            'access_level' => 'required|in:public,login_required,followers_only,private',
            'allow_comments' => 'boolean',
            'status' => 'required|in:draft,published',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:500',
        ]);

        // 生成slug
        if (empty($validated['slug'])) {
            $validated['slug'] = Str::slug($validated['title']);
        }

        // 处理特色图片上传
        if ($request->hasFile('featured_image')) {
            $validated['featured_image'] = $request->file('featured_image')->store('posts', 'public');
        }

        // 设置用户ID
        $validated['user_id'] = auth()->id();

        // 如果是发布状态，设置发布时间
        if ($validated['status'] === 'published') {
            $validated['published_at'] = now();
            // 普通用户发布的文章需要审核
            if (!in_array(auth()->user()->role, ['admin', 'editor'])) {
                $validated['is_approved'] = false;
                $validated['status'] = 'pending'; // 待审核状态
            } else {
                $validated['is_approved'] = true;
                $validated['approved_at'] = now();
                $validated['approved_by'] = auth()->id();
            }
        }

        // 计算阅读时间
        $validated['reading_time'] = $this->calculateReadingTime($validated['content']);

        // 创建文章
        $post = Post::create($validated);

        // 附加标签
        if (!empty($validated['tags'])) {
            $post->tags()->attach($validated['tags']);
        }

        // 更新用户文章数
        auth()->user()->increment('posts_count');

        return redirect()->route('profile.posts')
            ->with('success', $validated['status'] === 'pending' ? '文章已提交审核' : '文章发布成功');
    }

    /**
     * 显示编辑文章页面
     */
    public function edit(Post $post)
    {
        // 检查权限
        if ($post->user_id !== auth()->id() && !in_array(auth()->user()->role, ['admin', 'editor'])) {
            abort(403, '无权编辑此文章');
        }

        $categories = Category::where('is_active', true)->get();
        $tags = Tag::all();

        return Inertia::render('Post/Edit', [
            'post' => $post->load('tags'),
            'categories' => $categories,
            'tags' => $tags,
        ]);
    }

    /**
     * 更新文章
     */
    public function update(Request $request, Post $post)
    {
        // 检查权限
        if ($post->user_id !== auth()->id() && !in_array(auth()->user()->role, ['admin', 'editor'])) {
            abort(403, '无权编辑此文章');
        }

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:posts,slug,' . $post->id,
            'content' => 'required|string',
            'excerpt' => 'nullable|string|max:500',
            'category_id' => 'required|exists:categories,id',
            'tags' => 'array',
            'tags.*' => 'exists:tags,id',
            'featured_image' => 'nullable|image|max:2048',
            'access_level' => 'required|in:public,login_required,followers_only,private',
            'allow_comments' => 'boolean',
            'status' => 'required|in:draft,published',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string|max:500',
        ]);

        // 处理特色图片上传
        if ($request->hasFile('featured_image')) {
            // 删除旧图片
            if ($post->featured_image && Storage::exists($post->featured_image)) {
                Storage::delete($post->featured_image);
            }
            $validated['featured_image'] = $request->file('featured_image')->store('posts', 'public');
        }

        // 如果从草稿变为发布状态
        if ($post->status === 'draft' && $validated['status'] === 'published') {
            $validated['published_at'] = now();
            // 普通用户需要审核
            if (!in_array(auth()->user()->role, ['admin', 'editor'])) {
                $validated['is_approved'] = false;
                $validated['status'] = 'pending';
            }
        }

        // 计算阅读时间
        $validated['reading_time'] = $this->calculateReadingTime($validated['content']);

        // 更新文章
        $post->update($validated);

        // 更新标签
        $post->tags()->sync($validated['tags'] ?? []);

        return back()->with('success', '文章更新成功');
    }

    /**
     * 删除文章
     */
    public function destroy(Post $post)
    {
        // 检查权限
        if ($post->user_id !== auth()->id() && !in_array(auth()->user()->role, ['admin', 'editor'])) {
            abort(403, '无权删除此文章');
        }

        // 删除文章
        $post->delete();

        // 更新用户文章数
        auth()->user()->decrement('posts_count');

        return redirect()->route('profile.posts')->with('success', '文章删除成功');
    }

    /**
     * 计算阅读时间（分钟）
     */
    private function calculateReadingTime(string $content): int
    {
        $wordCount = str_word_count(strip_tags($content));
        $minutes = ceil($wordCount / 200); // 假设每分钟200字
        return max(1, $minutes);
    }
}